package com.iflytek.uoamp.notify.msg.format;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.iflytek.uoamp.common.notify.constant.ConfigName;
import com.iflytek.uoamp.common.notify.exception.NotifyException;
import com.iflytek.uoamp.common.notify.format.Formatter;
import com.iflytek.uoamp.common.notify.obj.MsgContent;
import com.iflytek.uoamp.common.notify.obj.Notification;
import com.iflytek.uoamp.common.notify.util.Configurator;

/**
 * 抽象类用于实现不同报文类型短信息的格式化,类中只存在pretty函数,该函数
 * 为抽象函数并无具体实现,具体的实现存在于格式化不同报文类型的子类中
 * @author allen
 *
 */
public abstract class FixedMsgFormatter implements Formatter {
	
    protected static final int TEMPLATE_ID = Configurator.getInstance().getPropertyByKey(ConfigName.SMS_TEMPLATEID, -1);
    protected List<?> contents;
    
    public String getContent(String text) {
        int pos = text.indexOf("@@");
        if(pos != -1) {
            return getReadableMsg(text.substring(pos + 2));
        } else {
            return getReadableMsg(text);
        }
    }
    
    /**
     * 如果采用短信模版则将JSON形式的字符串格式化为易于阅读的短信息内容,如果未使用
     * 短信息模版则直接返回content内容
     * @param content 短信息内容
     * @return content如果是模版形式的JSON字符串则返回格式化后的内容否则返回content自身
     * @throws NotifyException
     */
    private String getReadableMsg(String content){
        MsgContent msgContent = null;
        try {
            msgContent = JSON.parseObject(content, MsgContent.class);
        } catch(JSONException e) {
            return content;
        }
        
        StringBuilder builder = new StringBuilder();
        builder.append(msgContent.getMonitorTime());
        builder.append(msgContent.getMonitorType());
        builder.append(msgContent.getMonitorName());
        builder.append(msgContent.getState());
        builder.append(":");
        builder.append(msgContent.getStateDes());
        
        return builder.toString();
    }
    
    public abstract String pretty(Notification notification, List<?> contents) throws NotifyException;
}
